package cn.iocoder.yudao.module.book.service.records;

import cn.iocoder.yudao.module.book.controller.app.records.vo.AppRecordsRespVO;
import cn.iocoder.yudao.module.book.convert.AppRecordsConvert;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import cn.iocoder.yudao.module.book.controller.admin.records.vo.*;
import cn.iocoder.yudao.module.book.dal.dataobject.records.RecordsDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.book.dal.mysql.records.RecordsMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.book.enums.ErrorCodeConstants.*;

/**
 * 阅读记录 Service 实现类
 *
 * @author xi
 */
@Service
@Validated
public class RecordsServiceImpl implements RecordsService {

    @Resource
    private RecordsMapper recordsMapper;

    @Override
    public Integer createRecords(RecordsSaveReqVO createReqVO) {
        RecordsDO records = BeanUtils.toBean(createReqVO, RecordsDO.class);
        records.setUpdateTime(LocalDateTime.now());
//        如果存在记录，则更新时间
        RecordsDO record = recordsMapper.selectByBookId(createReqVO.getBookId(), createReqVO.getUserId().longValue());
        if(record!=null){
//            如果数据被删除了，先还原，再更新
            if(record.getDeleted()){
                recordsMapper.updateDeleted(record.getRecordId(),false);
            }
            recordsMapper.update( records, new UpdateWrapper<RecordsDO>().eq("record_id", record.getRecordId()));
        }else{
            // 不存在，插入
            records.setCreateTime(LocalDateTime.now());
            recordsMapper.insert(records);
        }
        // 返回
        return records.getRecordId();
    }

    @Override
    public void updateRecords(RecordsSaveReqVO updateReqVO) {
        // 校验存在
        validateRecordsExists(updateReqVO.getRecordId());
        // 更新
        RecordsDO updateObj = BeanUtils.toBean(updateReqVO, RecordsDO.class);
        recordsMapper.updateById(updateObj);
    }

    @Override
    public void deleteRecords(Integer id) {
        // 校验存在
        validateRecordsExists(id);
        // 删除
        recordsMapper.deleteById(id);
    }

    private void validateRecordsExists(Integer id) {
        if (recordsMapper.selectById(id) == null) {
            throw exception(RECORDS_NOT_EXISTS);
        }
    }

    @Override
    public RecordsDO getRecords(Integer id) {
        return recordsMapper.selectById(id);
    }

    @Override
    public PageResult<RecordsDO> getRecordsPage(RecordsPageReqVO pageReqVO) {
        return recordsMapper.selectPage(pageReqVO);
    }

    @Override
    public Boolean deleteByBookId(Integer id) {
        return recordsMapper.deleteByBookId(id) > 0;
    }

    @Override
    public Boolean deleteByCollectionId(Integer id) {
        return recordsMapper.deleteByCollectionId(id) > 0;
    }

    @Override
    public List<RecordsDO> selectDayRecord(Long userId, String time) {
        return recordsMapper.selectDayRecord(userId,time);
    }

    @Override
    public List<AppRecordsRespVO> getReadSummary(Long currentUserId) {
        return  BeanUtils.toBean(recordsMapper.selectByUserId(currentUserId), AppRecordsRespVO.class);
    }

    @Override
    public Boolean deleteByUserId(Long currentUserId) {
        List<RecordsDO> records =recordsMapper.selectByUserId(currentUserId);
        if(records.isEmpty()) throw exception(RECORDS_NOT_EXISTS);
        for(RecordsDO recordsDO:records){
            recordsMapper.deleteById(recordsDO.getRecordId());
        }
        return true;
    }

    @Override
    public List<AppRecordsRespVO> getRecentWeekRecords(Long currentUserId) {
        LocalDateTime sevenDaysAgo = LocalDateTime.now().minusDays(7);
        List<RecordsDO> list = recordsMapper.selectByUserIdAndCreateTimeAfter(currentUserId, sevenDaysAgo);
        return AppRecordsConvert.INSTANCE.convertList(list);
    }

    @Override
    public RecordsDO getByUserIdAndBookId(Long userId, Integer bookId) {
        return recordsMapper.selectByBookId(bookId, userId);
    }

//    @Override
//    public RecordsDO selectByBookId(Integer bookId) {
//        return recordsMapper.selectByBookId(bookId);
//    }

}